<template>
  <div class="payment-status">
    <h2>查询支付状态</h2>
    <el-form @submit.prevent="queryPayStatus" :model="formData" :rules="rules" ref="paymentForm">
      <el-form-item label="支付单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入支付单号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading">查询支付状态</el-button>
      </el-form-item>
    </el-form>

    <el-alert
        v-if="paymentStatus === 'CREATED'"
        title="支付单号已生成，但还未支付，请尽快完成支付。"
        type="warning"
        show-icon
    ></el-alert>
    <el-alert
        v-if="paymentStatus === 'No'"
        title="未找到支付单号，请先生成。"
        type="warning"
        show-icon
    ></el-alert>
    <el-alert
        v-if="paymentStatus === 'COMPLETED'"
        title="支付成功！谢谢您的购买。"
        type="success"
        show-icon
    ></el-alert>
    <el-alert
        v-if="paymentStatus === 'FAILED'"
        title="支付失败，请重试或联系支持人员。"
        type="error"
        show-icon
    ></el-alert>

    <el-alert v-if="error" :title="error" type="error" show-icon></el-alert>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

const store = useStore();

const formData = reactive({
  orderNo: '',
});

const loading = ref(false);
const paymentForm = ref(null);

const paymentStatus = computed(() => store.getters['queryPayStatus/getPaymentStatus']);
const error = computed(() => store.getters['payment/getError']);

const rules = {
  orderNo: [{ required: true, message: '请输入支付单号', trigger: 'blur' }],
};

const queryPayStatus = async () => {
  try {
    await paymentForm.value.validate();
    loading.value = true;

    const result = await store.dispatch('queryPayStatus/queryPayStatus', formData.orderNo);

    if (!result.success) {
      ElMessage.error(result.error || '查询支付状态失败');
    }
  } catch (err) {
    console.error('查询支付状态失败:', err);
    ElMessage.error(err.message || '查询支付状态失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.payment-status {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.el-form {
  margin-bottom: 20px;
}

.el-alert {
  margin-top: 20px;
}
</style>
